<template>
	<div class="ll-page">
		<n-alert type="warning" class="ll-tip" :show-icon="false" closable>
			注意：未进行探店设置-探店时间设置的产品不会在C端上线；已设置探店时间的，在探店开始时间显示在C端
		</n-alert>
		<!-- S 查询 -->
		<div class="ll-page-query flex justify-between">
			<n-form
				inline
				:model="formValue"
				label-placement="left"
				:show-feedback="false"
				class="flex-1 flex-wrap"
			>
				<n-form-item label="站点：" path="value">
					<n-select
						v-model:value="formValue.locationId"
						:options="options"
						filterable
						class="w-193px"
						@update:value="updateLocation"
					/>
				</n-form-item>
				<n-form-item label="产品：" path="value">
					<n-input
						v-model:value="formValue.keyWord"
						placeholder="输入产品名称/产品ID搜索"
						:autosize="true"
						class="w-291px"
						@keyup.enter="getTdProductList"
					/>
				</n-form-item>
			</n-form>
			<!--			<n-button color="rgba(0, 0, 0, 0.1)" text-color="#333333" @click="handelReset">重置</n-button>-->
		</div>
		<!-- E 查询 -->

		<!-- S 表格 -->
		<div class="ll-page-table">
			<n-data-table
				:columns="columns"
				:data="tabelData"
				:pagination="pagination"
				:remote="true"
				:loading="tableLoading"
				size="small"
				flex-height
				:scroll-x="1770"
				:style="{ height: '100%' }"
				@update:sorter="handleSorterChange"
			/>
		</div>
		<!-- E 表格 -->
		<!-- 查看详情 -->
		<ProductDetails v-model:modal="productDetailsModal" :product-id="productId" />
		<!-- 探店设置 -->
		<DiscoverySet
			v-model:modal="aiscoverySetModal"
			:product-id="productId"
			:commission-type-str="commissionTypeStr"
			@commit="getTdProductList"
		/>
		<!--        素材要求设置-->
		<MaterialConfig ref="materialConfig" @refresh="getTdProductList" />
	</div>
</template>
<script setup>
import { h, ref, reactive, nextTick, watch } from 'vue';
import { NButton, useMessage } from 'naive-ui';

import ProductDetails from './cmponents/ProductDetails.vue';
import DiscoverySet from './cmponents/DiscoverySet.vue';
import MaterialConfig from './cmponents/MaterialConfig.vue';
import dayjs from 'dayjs';
const message = useMessage();
//素材要求设置
const materialConfig = ref(null);
const openMaterialConfig = (row) => {
	if (row.startDate <= 0 || row.endDate <= 0) {
		message.error('请先完成探店设置后再进行素材要求设置！');
		return;
	}
	materialConfig.value.openMaterialConfig(row);
};

// 导入API接口
import {
	locationList,
	locationListFz,
	tdProductList,
	tdProductListFz,
	setSort
} from '@/api/product';
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router';

const router = useRouter();
const route = useRoute();

// 查询条件
const formValue = reactive({
	commissionType: null,
	endDate: null,
	keyWord: null,
	locationId: null,
	orderByField: 'sortShow',
	isOrderByAsc: 'ascend',
	pageIndex: 1,
	pageSize: 10,
	startDate: null
});

const options = ref([]);
// 获取站点数据
const getLocationList = async () => {
	const setForm = {
		city: ''
	};
	let res = null;
	if (router.currentRoute.value.fullPath === '/product/tdProductAdmin') {
		res = await locationList(setForm);
	} else if (router.currentRoute.value.fullPath === '/product/tdProductFz') {
		res = await locationListFz(setForm);
	}
	if (res && res.code === 0) {
		options.value = res.data.map((item) => {
			item.label = item.city;
			item.value = item.id;
			return item;
		});
		formValue.locationId = options.value[0].value;
	}
};

// 切换站点
const updateLocation = (locationId) => {
	formValue.locationId = locationId;
	formValue.pageIndex = 1;
	formValue.pageSize = 10;

	// 重置分页
	pagination.page = 1;
	getTdProductList();
};

const buttonHandle = (row, index) => {
	return formValue.orderByField === 'sortShow' && formValue.isOrderByAsc === 'ascend'
		? [
				h(
					NButton,
					{
						size: 'small',
						text: true,
						type: 'primary',
						style:
							index === 0
								? {
										marginRight: '8px',
										fontSize: '14px',
										display: 'none'
								  }
								: {
										marginRight: '8px',
										fontSize: '14px'
								  },
						onClick: () => sortMove(1, row, index)
					},
					{ default: () => '上移' }
				),
				h(
					NButton,
					{
						size: 'small',
						text: true,
						type: 'primary',
						style:
							index === tabelData.value.length - 1
								? {
										marginRight: '8px',
										display: 'none'
								  }
								: {
										marginRight: '8px'
								  },
						onClick: () => sortMove(2, row, index)
					},
					{ default: () => '下移' }
				)
		  ]
		: [];
};
// 表格
const columns = ref([
	{
		title: '站点',
		width: 100,
		key: 'siteName'
	},
	{
		title: '产品信息',
		width: 200,
		key: 'info',
		render(row) {
			return [h('div', {}, `ID：${row.productId}`), h('div', {}, `名称：${row.productName}`)];
		}
	},
	{
		title: '探店设置',
		key: 'setUp',
		width: 330,
		render(row) {
			return [
				h(
					'div',
					{},
					`探店时间：${
						row.startDate && row.endDate
							? dayjs.unix(row.startDate).format('YYYY-MM-DD HH:mm') +
							  '~' +
							  dayjs.unix(row.endDate).format('YYYY-MM-DD HH:mm')
							: '暂无'
					}`
				),
				h('div', { style: { display: 'flex' } }, getCommissionTypeStr(row)),
				h('div', {}, `备注：${row.productRemark ? row.productRemark : ''}`)
			];
		}
	},
	// {
	// 	title: '素材要求',
	// 	key: 'materialConfig',
	// 	width: 270,
	// 	render(row) {
	// 		return [
	// 			h(
	// 				'div',
	// 				{},
	// 				`上传日期：${
	// 					row.upResourceStartTime && row.upResourceEndTime
	// 						? dayjs.unix(row.upResourceStartTime).format('YYYY.MM.DD') +
	// 						  '~' +
	// 						  dayjs.unix(row.upResourceEndTime).format('YYYY.MM.DD')
	// 						: '暂无'
	// 				}`
	// 			),
	// 			h(
	// 				'div',
	// 				{},
	// 				`照片/视频定价：${
	// 					row.imgSalePrice >= 0 &&
	// 					row.videoSalePrice >= 0 &&
	// 					row.imgSalePrice !== null &&
	// 					row.videoSalePrice !== null
	// 						? '¥' + row.imgSalePrice / 100 + '/¥' + row.videoSalePrice / 100
	// 						: '暂无'
	// 				}`
	// 			),
	// 			h(
	// 				'div',
	// 				{},
	// 				`照片/视频平台收益：${
	// 					row.imgPlatformPercent >= 0 &&
	// 					row.videoPlatformPercent >= 0 &&
	// 					row.imgPlatformPercent !== null &&
	// 					row.videoPlatformPercent !== null
	// 						? row.imgPlatformPercent + '%/' + row.videoPlatformPercent + '%'
	// 						: '暂无'
	// 				}`
	// 			),
	// 			h(
	// 				'div',
	// 				{},
	// 				`照片/视频创作者收益：${
	// 					row.imgCreatorPercent >= 0 &&
	// 					row.videoCreatorPercent >= 0 &&
	// 					row.imgCreatorPercent !== null &&
	// 					row.videoCreatorPercent !== null
	// 						? row.imgCreatorPercent + '%/' + row.videoCreatorPercent + '%'
	// 						: '暂无'
	// 				}`
	// 			)
	// 		];
	// 	}
	// },
	{
		title: '探店份额',
		key: 'materialConfig',
		width: 270,
		render(row) {
			return [
				row.stock && h('div', {}, `到店份额：${row.stock}份（已用${row.saleCount}份）`),
				row.cloudStock &&
					h('div', {}, `云探店份额：${row.cloudStock}份（已用${row.cloudSaleCount}份）`)
			].filter(Boolean);
		}
	},
	{
		title: '探店素材',
		key: 'materialConfig',
		width: 270,
		render(row) {
			return [h('div', {}, `图片：${row.picNum}张`), h('div', {}, `视频：${row.videoNum}个`)];
		}
	},
	{
		title: '探店今日销量',
		key: 'todaySales',
		sortOrder: false,
		sorter: true,
		width: 120,
		align: 'center'
	},
	{
		title: '探店总销量',
		key: 'totalSales',
		sortOrder: false,
		sorter: true,
		width: 120,
		align: 'center'
	},
	// {
	// 	title: '素材昨日上传量',
	// 	key: 'resourceUploadCount',
	// 	sortOrder: false,
	// 	sorter: true,
	// 	width: 140,
	// 	align: 'center'
	// },
	// {
	// 	title: '素材昨日下载量',
	// 	key: 'resourceDownloadCount',
	// 	sortOrder: false,
	// 	sorter: true,
	// 	width: 140,
	// 	align: 'center'
	// },
	{
		title: '当前排序',
		key: 'sortShow',
		sortOrder: false,
		sorter: true,
		width: 120,
		align: 'center'
	},
	{
		title: '操作',
		key: 'actions',
		width: 230,
		fixed: 'right',
		render(row, index) {
			return [
				h(
					NButton,
					{
						size: 'small',
						text: true,
						type: 'primary',
						style: {
							marginRight: '8px',
							fontSize: '14px'
						},
						onClick: () => handelProductDetails(row)
					},
					{ default: () => '详情' }
				),
				h(
					NButton,
					{
						size: 'small',
						text: true,
						type: 'primary',
						style: {
							marginRight: '8px'
						},
						onClick: () => handelAiscoverySet(row)
					},
					{ default: () => '探店设置' }
				),
				// h(
				// 	NButton,
				// 	{
				// 		size: 'small',
				// 		text: true,
				// 		type: 'primary',
				// 		style: {
				// 			marginRight: '8px'
				// 		},
				// 		onClick: () => openMaterialConfig(row)
				// 	},
				// 	{ default: () => '素材要求设置' }
				// ),
				h(
					NButton,
					{
						size: 'small',
						text: true,
						type: 'primary',
						style:
							row.sortShow === 1
								? {
										marginRight: '8px',
										fontSize: '14px',
										display: 'none'
								  }
								: {
										marginRight: '8px',
										fontSize: '14px'
								  },
						onClick: () => sortMove(3, row)
					},
					{ default: () => '置顶' }
				)
			].concat(buttonHandle(row, index));
		}
	}
]);
const tabelData = ref([]);
const tableLoading = ref(false);

// 表格排序
const handleSorterChange = (sorter) => {
	columns.value.forEach((column) => {
		if (column.sortOrder === undefined) return;
		if (!sorter) {
			column.sortOrder = false;
			return;
		}
		if (column.sortOrder === undefined) return;
		if (!sorter) {
			column.sortOrder = false;
			return;
		}
		if (column.key === sorter.columnKey) {
			column.sortOrder = sorter.order;
			resetData();
			formValue.orderByField = sorter.order === false ? 'sortShow' : sorter.columnKey;
			formValue.isOrderByAsc = sorter.order === false ? 'ascend' : sorter.order;
			getTdProductList();
		} else {
			column.sortOrder = false;
		}
	});
};

const getCommissionTypeStr = (row) => {
	let dom = [];
	// [h('h1', 'A headline'), h('h1', 'A headline')];
	for (let index in row.commissionTypeList) {
		let item = row.commissionTypeList[index];
		if (item.commissionType === 1) {
			continue;
		}

		dom.push(h('div', item.commissionTypeStr));
	}
	return [h('span', '佣金规则：'), h('div', [...dom])];
};

// 分页
const pagination = reactive({
	page: 1,
	pageSize: formValue.pageSize,
	pageSizes: [10, 20, 30, 40],
	showSizePicker: true,
	itemCount: 0,
	prefix({ itemCount }) {
		return `共${itemCount}条`;
	},
	onChange: (page) => {
		pagination.page = page;
		formValue.pageIndex = page;
		getTdProductList();
	},
	onPageSizeChange: (pageSize) => {
		pagination.pageSize = pageSize;
		formValue.pageSize = pageSize;
		formValue.pageIndex = 1;
		pagination.page = 1;
		getTdProductList();
	}
});

// 获取列表
const getTdProductList = async () => {
	let res = null;
	tableLoading.value = true;
	if (router.currentRoute.value.fullPath === '/product/tdProductAdmin') {
		res = await tdProductList(formValue);
	} else if (router.currentRoute.value.fullPath === '/product/tdProductFz') {
		res = await tdProductListFz(formValue);
	}
	console.log(res);
	tableLoading.value = false;
	if (res && res.code === 200) {
		tabelData.value = res.data.productList;
		pagination.itemCount = res.data.total;
	}
};
// 重置
const handelReset = () => {
	getTdProductList();
};

// 初始化数据
const initData = async () => {
	await getLocationList();
	await getTdProductList();
};

// 初始化数据
const resetData = () => {
	formValue.pageIndex = 1;
	formValue.pageSize = 10;
	formValue.orderByField = 'sortShow';
	formValue.isOrderByAsc = 'ascend';

	// 重置分页
	pagination.page = 1;

	// 弹框
	productDetailsModal.value = false;
	aiscoverySetModal.value = false;
};

nextTick(() => {
	initData();
});

// 监听路由变化
watch(
	() => route.fullPath,
	(n, o) => {
		pagination.page = 1;
		// formValue.orderByField === 'sortShow' && formValue.isOrderByAsc === 'ascend'
		console.log(formValue.orderByField);
		console.log(formValue.isOrderByAsc);
		resetData();
		initData();
	}
);

// 查看详情
const productDetailsModal = ref(false);
const productId = ref(0);
const handelProductDetails = (res) => {
	productDetailsModal.value = true;
	productId.value = res.productId;
};

// 探店设置
const aiscoverySetModal = ref(false);
const commissionTypeStr = ref('');
const handelAiscoverySet = (res) => {
	aiscoverySetModal.value = true;
	productId.value = res.productId;
	commissionTypeStr.value = res.commissionTypeStr;
};

// 上移
const sortMove = (type, row, index) => {
	if (type === 1 && index === 0) {
		message.error('该条数据已无法继续上移！');
		return;
	}
	if (type === 2 && index === tabelData.value.length - 1) {
		message.error('该条数据已无法继续下移！');
		return;
	}
	const params = { currentSortId: row.currentSortId, opType: type };
	// 上移
	if (type === 1) {
		let topRow = tabelData.value[index - 1];
		params.nearCurrentSortId = topRow.currentSortId;
	}
	// 下移
	if (type === 2) {
		let downRow = tabelData.value[index + 1];
		params.nearCurrentSortId = downRow.currentSortId;
	}
	// 置顶
	if (type === 3) {
		params.nearCurrentSortId = null;
	}
	const moveSort = async () => {
		const res = await setSort(params);
		if (res.code === 200) {
			message.success('操作成功');
			getTdProductList();
		}
	};
	moveSort();
};
</script>

<style lang="less" scoped>
.ll-page {
	height: 100%;
	flex-direction: column;
	display: flex;
	background-color: #ffffff;
	&-query {
		background: @bg;
		padding: @padding-10;
		margin-right: 10px;
		margin-left: 10px;
		margin-top: 10px;
		border-radius: 3px;
		border: 1px solid #f0f0f0;
	}
	&-table {
		padding: 10px;
		overflow: hidden;
		flex: 1 1 0%;
	}
}

.ll-tip {
	margin-right: 10px;
	margin-left: 10px;
	margin-top: 10px;
	::v-deep(.n-alert-body) {
		padding: 8px;
		.n-alert-body__content {
			font-size: 12px;
			color: #f5894e;
		}
	}
	::v-deep(.n-alert__close) {
		right: -6px;
		top: -3px;
		color: #f5894e;
	}
}
</style>
